import axios from "axios";
import cookie from "react-cookies";
import {Token} from "@/app/constants/authTokenConstants";

/**
 * axios封装【request和response】
 */
export default function useRequest() {
    /*创建一个axios*/
    const axiosInstance = axios.create({
        baseURL: '/',
        timeout: 5000
    })

    /*对所有Post请求加Header*/
    axiosInstance.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';

    /*统一请求拦截器*/
    axiosInstance.interceptors.request.use(config => {
        const token = cookie.load(Token);/*获取Token*/
        if (config && config.headers) { // 多一步判断
            if (token) config.headers['Authorization'] = token
        }/*存在则加到Header*/
        return config;
    }, error => {
        return Promise.reject(error);
    });

    /*统一响应拦截器*/
    axiosInstance.interceptors.response.use(response => {
        if (response.statusText === 'OK') {
            return Promise.resolve(response)
        } else {
            return Promise.reject(response.data.message)
        }
    }, error => {
        if (error.response) {
            return Promise.reject(error);
        } else {
            return Promise.reject('请求超时，请稍后重试');
        }
    });
    return axiosInstance;
}